﻿using System;
using System.Threading.Tasks;
using Devonline.Core;
using Devonline.Entity;
using Devonline.Http;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.AspNetCore.OData.Routing.Controllers;
using ProjectManagement.Models;

namespace ProjectManagement.Controllers
{
    [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
    public class ParametersController : ODataController
    {
        private readonly ApplicationDbContext _context;

        public ParametersController(ApplicationDbContext context)
        {
            _context = context;
        }

        [EnableQuery]
        public IActionResult Get()
        {
            return Ok(_context.Parameters);
        }

        [EnableQuery]
        public async Task<IActionResult> Post([FromBody] Parameter entitySet)
        {
            if (entitySet == null)
            {
                throw new Exception($"{typeof(Parameter).GetDisplayName()} 不能为空!");
            }

            await _context.UniqueAsync<Parameter, string>(entitySet);
            entitySet.Create();
            _context.Add(entitySet);
            await _context.SaveChangesAsync().ConfigureAwait(true);
            return Ok(entitySet);
        }

        [EnableQuery]
        public async Task<IActionResult> Put(string key, [FromBody] Parameter entitySet)
        {
            var displayName = typeof(Issue).GetDisplayName();
            if (entitySet == null)
            {
                throw new Exception($"{displayName} 不能为空!");
            }

            var original = await _context.Parameters.FindAsync(key);
            if (original == null)
            {
                throw new Exception($"{displayName} 中当前记录不存在!");
            }

            await _context.UniqueAsync<Parameter, string>(entitySet);

            entitySet.CopyTo(original);
            _context.Update(original);
            await _context.SaveChangesAsync();
            return Ok(original);
        }

        [EnableQuery]
        public async Task<IActionResult> Delete(string key)
        {
            var displayName = typeof(Parameter).GetDisplayName();
            var entitySet = await _context.Parameters.FindAsync(key);
            if (entitySet == null)
            {
                throw new Exception($"{displayName} 中当前记录不存在!");
            }

            _context.Remove(entitySet);
            await _context.SaveChangesAsync().ConfigureAwait(true);
            return Ok();
        }
    }
}
